//
//  MeChangeInfoViewController.m
//  BGM
//
//  Created by liuqin on 2018/11/30.
//  Copyright © 2018年 com.alirtc.demo. All rights reserved.
//

#import "MeChangeInfoViewController.h"
#import "Common.h"
#import "BGMUser.h"
#import "BGMHTTP.h"
#import "MeTableViewCell.h"
#import "AFHTTPSessionManager.h"
#import "MeChangeInfoView.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "MePhotosViewController.h"
#import "GFAddressPicker.h"
#import "BGMNewImage.h"
#import "PushImageClass.h"
#import "GCQiniuUploadManager.h"
#import "QiniuSDK.h"


@interface MeChangeInfoViewController ()
<UITableViewDelegate,
UITableViewDataSource,
MeChangeInfoViewDelegate,
UINavigationControllerDelegate,
UIImagePickerControllerDelegate,
GFAddressPickerDelegate>

@property (nonatomic,strong)UITableView *meTableView;
@property (nonatomic,strong)NSArray *array;

@property (nonatomic,strong)MeChangeInfoView *changBgView;
@property (nonatomic, strong)NSString *userName; //姓名
@property (nonatomic, strong)UIImage *userImage; //用户头像

@property (nonatomic, strong)NSString *userImageURL; //用户头像

@property (nonatomic, strong)NSString *userSex; //用户性别

@property (nonatomic, strong)NSString *user_industry; //用户行业
@property (nonatomic, strong)NSString *birth;
@property (nonatomic, strong)NSString *userCity;


@property (nonatomic, strong)NSMutableArray *userOldTitles;  //用户个人标签 已选
@property (nonatomic, strong)NSMutableArray *userChangeTitles;  //用户个人标签 记录选中状态
@property (nonatomic, strong)NSMutableString *resultUserTitles;  //用户个人标签 修改后最终结果

@property (nonatomic, strong)NSMutableArray *user_title; //用户标签
@property (nonatomic, strong)GFAddressPicker *pickerView;

@end

@implementation MeChangeInfoViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}
- (void)chageimageArray{
    
                  NSIndexPath *indexPath=[NSIndexPath indexPathForRow:1 inSection:0];
    
    [self.meTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navview.hidden = NO;
    self.titleBtn.hidden = NO;
    CGRect rect = self.titleBtn.frame;
    rect.size.width = rect.size.width+70;
    self.titleBtn.frame = rect;
    [self.titleBtn setTitle:@"修改资料" forState:UIControlStateNormal];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(chageimageArray) name:@"chageimageArray" object:nil];
    
    
    self.array = @[@"头像",@"照片墙",@"姓名",@"性别",@"生日",@"城市",@"行业",@"个人标签"];
    BGMUser *user = [BGMUser shareInstance];
 
    self.resultUserTitles = [[NSMutableString alloc]init];
    self.userOldTitles = [[NSMutableArray alloc]initWithArray:user.personalLabelArray];
    self.userChangeTitles = [[NSMutableArray alloc]init];
    BOOL isHave = NO;
    for (NSDictionary *titleDic in self.userTitles) {
        NSString *userTitle = [NSString stringWithFormat:@"%@",[titleDic objectForKey:@"lableName"]];
        isHave = NO;
        for (NSString *oldTitle in self.userOldTitles) {
            if ([oldTitle isEqualToString:userTitle]) {
                isHave = YES;
                break;
            }else{
                isHave = NO;
            }
            
        }
        if (isHave) {
            [self.userChangeTitles addObject:@"1"];
        }else{
            [self.userChangeTitles addObject:@"0"];
        }
    }

    self.userName = user.name;
    self.userSex =user.gender;
    self.user_industry = user.industry;
    self.user_title = [[NSMutableArray alloc]initWithArray:user.personalLabelArray];
    self.birth =user.birthday;
    self.userImageURL =user.headImage;
    self.userCity = user.city;
    self.meTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.navview.frame.size.height, SCREENW, SCREENH-self.navview.frame.size.height)];
    self.meTableView.backgroundColor = [UIColor clearColor];
    self.meTableView.delegate = self;
    self.meTableView.dataSource = self;
    self.meTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.meTableView];
    
    
    self.changBgView = [[MeChangeInfoView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
    self.changBgView.hidden = YES;
    self.changBgView.delegate = self;
    [self.view addSubview:self.changBgView];
    
    
    self.pickerView = [[GFAddressPicker alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.pickerView.delegate = self;
    self.pickerView.font = [UIFont boldSystemFontOfSize:18];
    [self.view addSubview:self.pickerView];
    self.pickerView.hidden = YES;
    
}
#pragma mark tableViewDelgate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 8;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"MeTableViewCell";
    MeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell ==nil) {
        cell = [[MeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.rightLabel.hidden = NO;
        cell.rightLabel.backgroundColor = [UIColor clearColor];
        cell.rightLabel.frame = CGRectMake(SCREENW/2, 0, SCREENW/2-40, 50);
    }
    cell.rightImageBtn.hidden = YES;
    [cell.iconBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"info_%d",(int)indexPath.row]] forState:UIControlStateNormal];
    cell.contentLabel.text =[self.array objectAtIndex:indexPath.row];
 
    BGMUser *user = [BGMUser shareInstance];
    int tag = (int)indexPath.row;
    switch (tag) {
        case 0:  //头像
        {
            cell.rightImageBtn.hidden = NO;
           
            if (self.userImage == nil) {
                [cell.rightImageBtn sd_setImageWithURL:[NSURL URLWithString:self.userImageURL] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"headImage"]];
            }else{
                [cell.rightImageBtn setImage:self.userImage forState:UIControlStateNormal];
            }
        }
            break;
        case 1:  //照片墙
        {
            id imageArray = [BGMUser shareInstance].imageArray;
            if ([imageArray isKindOfClass:[NSArray class]]) {
                NSArray *array = imageArray;
                cell.rightLabel.text = [NSString stringWithFormat:@"%d/9",(int)array.count];

            }else{
                NSString *str = imageArray;
                if (str.length == 0) {
                    cell.rightLabel.text = @"0/9";
                }else{
                    cell.rightLabel.text = @"1/9";

                }
            }

        }
            break;
        case 2: //姓名
        {
            cell.rightLabel.text = user.name;

        }
            break;
        case 3:  //性别
        {
            cell.rightLabel.text = [user.gender isEqualToString:@"1"] ? @"男" : @"女";
        }
            break;
        case 4: //生日
        {
            cell.rightLabel.text = user.birthday;

        }
            break;
        case 5://城市
        {
            cell.rightLabel.text = self.userCity;

        }
            break;
        case 6: //行业
        {
            cell.rightLabel.text = user.industry;

        }
            break;
        case 7://个人标签
        {
            NSMutableString *str = [[NSMutableString alloc]init];
            for (NSString *str1 in user.personalLabelArray) {
                [str appendString:[NSString stringWithFormat:@"%@、",str1]];
            }
            
            cell.rightLabel.text = str;

        }
            break;
            
        default:
            break;
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    int tag = (int)indexPath.row;
    switch (tag) {
        case 0:  //头像
        {
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                           message:nil
                                                                    preferredStyle:UIAlertControllerStyleActionSheet];
            
            UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消 " style:UIAlertActionStyleCancel
                                                                 handler:^(UIAlertAction * action) {
                                                                     //响应事件
                                                                     NSLog(@"action = %@", action);
                                                                 }];
            UIAlertAction* deleteAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault
                                                                 handler:^(UIAlertAction * action) {
                                                                     //响应事件
//                                                                     NSLog(@"action = %@", action);
                                                                     [self seleHeadImage:1];
                                                                 }];
            UIAlertAction* saveAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault
                                                               handler:^(UIAlertAction * action) {
                                                                   //响应事件
//                                                                   NSLog(@"action = %@", action);
                                                                    [self seleHeadImage:2];
                                                               }];
            [alert addAction:saveAction];
            [alert addAction:cancelAction];
            [alert addAction:deleteAction];
            [self presentViewController:alert animated:YES completion:nil];
            
        
            
         }
            break;
        case 1:  //照片墙
        {
            MePhotosViewController *vc = [[MePhotosViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 2: //姓名
        {
            self.changBgView.hidden = NO;
            self.changBgView.nameView.hidden = NO;
            
            self.changBgView.sexView.hidden = YES;
            self.changBgView.TitleView.hidden = YES;
            self.changBgView.dateView.hidden = YES;
        }
            break;
        case 3:  //性别
        {
            self.changBgView.hidden = NO;
            self.changBgView.nameView.hidden = YES;
            self.changBgView.sexView.hidden = NO;
            self.changBgView.TitleView.hidden = YES;
            self.changBgView.dateView.hidden = YES;

            if ([[BGMUser shareInstance].gender isEqualToString:@"1"]) {
                [self.changBgView setUserSex:YES];
            }else{
                 [self.changBgView setUserSex:NO];
            }
//
        }
            break;
        case 4: //生日
        {
 
            self.changBgView.hidden = NO;
            self.changBgView.nameView.hidden = YES;
            self.changBgView.sexView.hidden = YES;
            self.changBgView.TitleView.hidden = YES;
            self.changBgView.isTitle = YES;
            self.changBgView.dateView.hidden = NO;

            

        }
            break;
        case 5://城市
        {
            self.pickerView.hidden = NO;
        }
            break;
        case 6: //行业
        {
            self.changBgView.hidden = NO;
            self.changBgView.nameView.hidden = YES;
            self.changBgView.sexView.hidden = YES;
            self.changBgView.TitleView.hidden = NO;
            self.changBgView.userTitle.text = @"行业";
            self.changBgView.titleContents = self.userIntrys;
            self.changBgView.isTitle = YES;
            self.changBgView.dateView.hidden = YES;

            [self.changBgView.userTable reloadData];

        }
            break;
        case 7://个人标签
        {
            self.changBgView.hidden = NO;
            self.changBgView.nameView.hidden = YES;
            self.changBgView.sexView.hidden = YES;
            self.changBgView.TitleView.hidden = NO;
            self.changBgView.userTitle.text = @"个性标签";
            self.changBgView.isTitle = NO;
            self.changBgView.dateView.hidden = YES;
            self.changBgView.titleContents = self.userTitles;
            self.changBgView.userSeleArray = self.userChangeTitles;
            [self.changBgView.userTable reloadData];

            
        }
            break;
            
        default:
            break;
    }
}

#pragma mark s修改标签
-(void)changeUserLabel:(NSMutableArray *)array{
 
    for (int i = 0; i<array.count; i++) {
        NSString *str = [array objectAtIndex:i];
        if ([str isEqualToString:@"1"]) {
            NSDictionary *dic = [self.userTitles objectAtIndex:i];
            [self.resultUserTitles appendString:[NSString stringWithFormat:@"%@,",[dic objectForKey:@"lableName"]]];
        }
    }
     [self changeUserInfo];
     self.changBgView.hidden = YES;

}

#pragma mark 修改个人头像
//1拍 2 选
- (void)seleHeadImage:(int)i {

    // 判断系统是否支持相机
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self; //设置代理
    imagePickerController.allowsEditing = YES;
    if (i == 1) {
        //拍照
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }else {
        //相册
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
    

}
// 获取图片后操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    if ([mediaType isEqualToString:(NSString *) kUTTypeImage] && picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImage *edit = [info objectForKey:UIImagePickerControllerEditedImage];
        self.userImage = edit;
         NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
         [self.meTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
 
     }else if ([mediaType isEqualToString:(NSString *) kUTTypeImage] && picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary){
         
         UIImage *edit = [info objectForKey:UIImagePickerControllerEditedImage];
         self.userImage = edit;
         NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
         [self.meTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
       }
    // 销毁控制器
    [self upImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"我点击了关闭");
}
// 上面保存图片或录像的方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    NSLog(@"保存图片完成");
}

/** 代理方法返回省市区*/
- (void)GFAddressPickerWithProvince:(NSString *)province
                               city:(NSString *)city area:(NSString *)area{
    
    self.userCity = city;
    [self changeUserInfo];
    self.pickerView.hidden = YES;


}
/** 取消代理方法*/
- (void)GFAddressPickerCancleAction{
    self.pickerView.hidden = YES;
}

-(void)hideUserLabel{
    self.changBgView.hidden = YES;

}
#pragma mark  修改头像
- (void)upImage{
    
    BGMNewImage *newImage = [[BGMNewImage alloc]init];
    NSData *data = [newImage resetSizeOfImageData:self.userImage maxSize:1024];
    NSString *token =  [[GCQiniuUploadManager sharedInstance] createToken];
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    QNUploadOption *up = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%0.f", a];//转为字符型
    NSString *name = [NSString stringWithFormat:@"%@_iosUserHead.png",timeString];
    
    [upManager putData:data key:name token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        NSString *url = [NSString stringWithFormat:@"http://yaobangma.com/%@",[resp objectForKey:@"key"]];
        self.userImageURL = url;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self changeUserInfo];
        });
    } option:up];
}
#pragma mark  姓名
- (void)changeName:(NSString *)newName{
    if(![newName isEqualToString:[BGMUser shareInstance].name]){
        self.userName = newName;
        [self changeUserInfo];
        [BGMUser shareInstance].name = self.userName;
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:2 inSection:0];
        [self.meTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }
    self.changBgView.hidden = YES;
    
}
#pragma mark 性别  1男2女
-(void)changeSex:(NSString *)sex{
    if(![sex isEqualToString:[BGMUser shareInstance].gender]){
        self.userSex = sex;
        [self changeUserInfo];
        [BGMUser shareInstance].gender = self.userSex;
        
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:3 inSection:0];
        [self.meTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }
    self.changBgView.hidden = YES;
}
#pragma mark 修改行业
-(void)changeIndustry:(NSString *)industry{
    if(![industry isEqualToString:[BGMUser shareInstance].industry]){
        self.user_industry = industry;
        [self changeUserInfo];
        [BGMUser shareInstance].industry = self.user_industry;
        NSIndexPath *indexPath=[NSIndexPath indexPathForRow:6 inSection:0];
        [self.meTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    }
    self.changBgView.hidden = YES;
    
}
#pragma mark 生日
-(void)changeBirth:(NSString *)birth{
    if (birth.length != 0) {
        self.birth = birth;
        [self changeUserInfo];
    }
    self.changBgView.hidden = YES;
}

#pragma mark 发送请求
- (void)changeUserInfo{
    NSString *userToken = [BGMUser shareInstance].userToken;
    NSString *userID = [BGMUser shareInstance].userId;
    NSMutableString *imageStr = [[NSMutableString alloc]init];
    for (NSString *imageS in [BGMUser shareInstance].imageArray) {
        [imageStr appendString:[NSString stringWithFormat:@"%@,",imageS]];
    }
    
    NSDictionary *dic = @{@"userToken":userToken,
                          @"userId":userID,
                          @"nickName":@"",
                          @"image":imageStr,
                          @"name":self.userName,
                          @"gender":self.userSex,
                          @"birthday":self.birth,
                          @"city":self.userCity,
                          @"industry":self.user_industry,
                          @"personalLabel":self.resultUserTitles,
                          @"headImage":self.userImageURL
                          };
    [BGMHTTP requestWithMethodName:@"users/editUserInfo" parameters:dic completion:^(BOOL success, NSError *error, NSDictionary *result) {
        [self saveInfomation:result];
    }];
}
#pragma mark 保存个人信息
- (void)saveInfomation:(NSDictionary *)dictory{
    NSDictionary *dic = [dictory objectForKey:@"data"];
    BGMUser *user = [BGMUser shareInstance];
    user.birthday = [NSString stringWithFormat:@"%@",[dic objectForKey:@"birthday"]];
    user.city = [NSString stringWithFormat:@"%@",[dic objectForKey:@"city"]];
    user.gender = [NSString stringWithFormat:@"%@",[dic objectForKey:@"gender"]];
    user.headImage = [NSString stringWithFormat:@"%@",[dic objectForKey:@"headImage"]];
    user.imageArray = [dic objectForKey:@"image"];///////////////////////////
    user.industry = [NSString stringWithFormat:@"%@",[dic objectForKey:@"industry"]];
    user.name = [NSString stringWithFormat:@"%@",[dic objectForKey:@"name"]];
    user.personalLabelArray =[dic objectForKey:@"personalLabel"];
    user.phone = [NSString stringWithFormat:@"%@",[dic objectForKey:@"phone"]];
    user.spectralValue = [NSString stringWithFormat:@"%@",[dic objectForKey:@"spectralValue"]];
    user.userHelpSize = [NSString stringWithFormat:@"%@",[dic objectForKey:@"userHelpSize"]];
    user.userPublishAcceptancesSize = [NSString stringWithFormat:@"%@",[dic objectForKey:@"userPublishAcceptancesSize"]];
    user.userPublishSize = [NSString stringWithFormat:@"%@",[dic objectForKey:@"userPublishSize"]];
    
    [self.meTableView reloadData];
}

@end
